package org.duiduo.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.duiduo.constant.BaseConstant;
import org.duiduo.constant.ResponseConstants;
import org.duiduo.pojo.TbUser;
import org.duiduo.repository.TbUserRepository;
import org.duiduo.result.ResultData;
import org.duiduo.service.TbUserService;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * Service层
 * 
 * @author 夜泷noga
 */
@Slf4j
@Service(value = "TbUserServiceImpl")
public class TbUserServiceImpl implements TbUserService {
	
	@Autowired
	private TbUserRepository repository;

	@Resource
	private Redisson redisson;

	@Override
	public List<TbUser> getList(String username) {
		// TODO Auto-generated method stub
		TbUser user = TbUser.builder()
				.username(username)
				.build();
		ExampleMatcher matcher = ExampleMatcher.matching()
				.withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains());
		Example<TbUser> example = Example.of(user, matcher);
		return repository.findAll(example);
	}

	@Override
	public void delete(Integer id) {
		// TODO Auto-generated method stub
		repository.deleteById(id);
	}

	@Override
	public ResultData addOrEdit(TbUser user) {
		// TODO Auto-generated method stub
		String lockName = BaseConstant.TB_USER_ADD_EDIT_LOCK;
		// 锁
		RLock lock = null;
		try {
			lock = redisson.getLock(lockName);
			if (lock.tryLock()) {
				// 睡眠1分钟
//				Thread.sleep(600000);
				// 保存
				repository.saveAndFlush(user);
				return ResultData.success();
			}
			return ResultData.error(ResponseConstants.Resp.RESP_02.getCode(), ResponseConstants.Resp.RESP_02.getMessage());
		} catch (Exception e) {
			log.error("异常:", e);
			return ResultData.error(ResponseConstants.Resp.RESP_01.getCode(), ResponseConstants.Resp.RESP_01.getMessage());
		} finally {
			// 释放锁
			if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()) {
				lock.unlock();
			}
		}
	}

	@Override
	public TbUser findById(Integer id) {
		// TODO Auto-generated method stub
		return repository.findById(id).get();
	}

    @Override
    public TbUser getByUsernameAndPassword(String username, String password) {
		TbUser user = TbUser.builder()
				.username(username)
				.password(password)
				.build();
		Example<TbUser> example = Example.of(user);
		List<TbUser> all = repository.findAll(example);
		return CollectionUtils.isEmpty(all) ? null : all.get(0);
    }

}
